
package com.rh.soc.assetthirdinterface.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.rh.soc.assetcommon.model.AssetRemoteConfigVO;
import com.rh.soc.assetmanage.model.AssetAppendVO;
import com.rh.soc.assetmanage.model.AssetReturnVO;
import com.rh.soc.assetmanage.model.AssetVO;
import com.rh.soc.assetmanage.model.BorrowVO;
import com.rh.soc.assetmanage.model.CustomPropertyVO;
import com.rh.soc.assetmanage.model.IpVO;
import com.rh.soc.assetmanage.model.SnmpVO;
import com.rh.soc.assetmanage.service.IAssetService;
import com.rh.soc.assetthirdinterface.model.AssetInfoVO;
//import com.rh.soc.license.LicInfoUtil;
import com.rh.soc.monitor.config.model.MonitorVO;
import com.rh.webserver.common.base.bean.AppResultBean;
import com.rh.webserver.common.base.component.LicInfoUtil;
import com.rh.webserver.common.base.controller.BaseController;
import com.rh.webserver.common.base.exception.AppException;
import com.rh.webserver.common.base.json.IDataCenter;
import com.rh.webserver.common.util.BeanUtils;
import com.rh.webserver.common.util.JsonUtil;
import com.rh.webserver.common.util.StringUtil;

@Controller
@RequestMapping("/third/AssetOperation")
public class AssetThirdInterfaceController extends BaseController {

	@Resource
	private IAssetService assetservice;

	/**
	 * 批量添加资产
	 */
	@RequestMapping("batchAddAsset")
	@ResponseBody
	public AppResultBean batchAddAsset(@RequestParam("param") String param, HttpSession session,
			HttpServletRequest request) throws Exception {
		logger.info("param=[" + param + "]");
		AppResultBean bean = new AppResultBean();
		IDataCenter idc = BeanUtils.toDataCenter(param);
		Map<String, AppResultBean> resultMap = new HashMap<String, AppResultBean>();
		int errorCount = 0;
		try {
			List<AssetInfoVO> assetinfoList = (List<AssetInfoVO>) BeanUtils.jsonToBeans(idc, "assetinfos",
					AssetInfoVO.class);
			for (int i = 0; i < assetinfoList.size(); i++) {

				AssetInfoVO assetInfoVo = assetinfoList.get(i);
				AssetVO assetVo = changeAssetInfoVOtoAssetVo(assetInfoVo);
				AssetAppendVO assetAppendVo = changeAssetInfoVOtoAssetAppendVo(assetInfoVo);
				assetVo.setAssetAllowedNum(LicInfoUtil.queryAssetAllowedNum(request));
				SnmpVO assetSnmpVo = new SnmpVO();
				List<CustomPropertyVO> list = new ArrayList<CustomPropertyVO>();
				BorrowVO borrowVo = new BorrowVO();

				AssetRemoteConfigVO telnetVo = new AssetRemoteConfigVO();
				AssetRemoteConfigVO sshVo = new AssetRemoteConfigVO();
				AssetRemoteConfigVO wmiVo = new AssetRemoteConfigVO();
				AssetRemoteConfigVO trayVo = new AssetRemoteConfigVO();

				// telnet 0 SSH 1 wmi 2 tray 3
				if (telnetVo != null)
					telnetVo.setConnectType("0");
				if (sshVo != null)
					sshVo.setConnectType("1");
				if (wmiVo != null)
					wmiVo.setConnectType("2");
				if (trayVo != null)
					trayVo.setConnectType("3");
				assetVo.setOperator(getUserId(session));
				assetVo.setUserId(getUserId(session));

				assetservice.setBatch(false);
				AssetReturnVO errorInfo = assetservice.addAsset(assetVo, assetAppendVo, assetSnmpVo, list, borrowVo,
						telnetVo, sshVo, wmiVo, trayVo);
				String buttonType = (String) idc.getParameter("buttonType");
				if (("save".equals(buttonType) || "next".equals(buttonType)) && errorInfo.getConflict() == 0) {
					assetVo.setEdId(errorInfo.getEdId());
					AssetVO vo = assetservice.queryAssetDetailAdd(assetVo);
					vo.setIpList(null);
					vo.setAssetAppend(null);
					vo.setSnmp(null);
					vo.setCustomPropertyList(null);
					setStoreRowData(bean, "assetStore", vo);
				}
				if (errorInfo.getConflict() == 0) {
					AppResultBean resultBean = new AppResultBean();
					resultBean.ok("添加同步成功。");
					resultMap.put(assetVo.getEdId(), resultBean);
				} else if (errorInfo.getConflict() == 1) {
					String rtnMessage = "";
					for (AssetReturnVO error : errorInfo.getConfIPList()) {
						rtnMessage += "资产IP" + error.getIp() + "与域" + error.getDomainName() + "下的"
								+ error.getAssetName() + "的IP重复。<br>";
					}
					AppResultBean resultBean = new AppResultBean();
					resultBean.fail(rtnMessage);
					resultMap.put(assetVo.getEdId(), resultBean);
					errorCount++;

				} else if (errorInfo.getConflict() == 2) {

					// bean.fail("资产主IP与" + errorInfo.getDomainName() + "下的网段" +
					// errorInfo.getIpSection() + "有重复，请修改后再保存。");

					AppResultBean resultBean = new AppResultBean();
					resultBean.fail(
							"资产主IP与" + errorInfo.getDomainName() + "下的网段" + errorInfo.getIpSection() + "有重复，请修改后再保存。");
					resultMap.put(assetVo.getEdId(), resultBean);
					errorCount++;
				} else if (errorInfo.getConflict() == 4) {

					// bean.fail("资产所属的多个安全域必须隶属于不同的代理。<br>" +
					// errorInfo.getConflictMessage().toString());

					AppResultBean resultBean = new AppResultBean();
					resultBean.fail("资产所属的多个安全域必须隶属于不同的代理。<br>" + errorInfo.getConflictMessage().toString());
					resultMap.put(assetVo.getEdId(), resultBean);
					errorCount++;

				} else if (errorInfo.getConflict() == 5) {

					// bean.fail("启用的资产数量已经达到License允许的最大数量，资产不能启用。");
					AppResultBean resultBean = new AppResultBean();
					resultBean.fail("启用的资产数量已经达到License允许的最大数量，资产不能启用。");
					resultMap.put(assetVo.getEdId(), resultBean);
					errorCount++;

				} else if (errorInfo.getConflict() == 6) {

					// bean.fail("资产编号与资产名称为" + errorInfo.getAssetName() +
					// "的资产编号重复，请修改后再同步。");
					AppResultBean resultBean = new AppResultBean();
					resultBean.fail("资产编号与资产名称为" + errorInfo.getAssetName() + "的资产编号重复，请修改后再同步。");
					resultMap.put(assetVo.getEdId(), resultBean);
					errorCount++;

				} else {
					// bean.fail("同步添加失败。");
					AppResultBean resultBean = new AppResultBean();
					resultBean.fail("同步添加失败");
					resultMap.put(assetVo.getEdId(), resultBean);
					errorCount++;

				}
			}
		} catch (AppException e) {
			bean.fail("添加失败。");
			logger.error(e.getMessage(), e);
		}
		bean.ok(resultMap);
		return bean;
	}

	/**
	 * 
	 * 批量修改资产
	 */
	@RequestMapping("batchUpdAsset")
	@ResponseBody
	public AppResultBean batchUpdAsset(@RequestParam("param") String param, HttpSession session,
			HttpServletRequest request) throws Exception {

		logger.info("param=[" + param + "]");

		AppResultBean bean = new AppResultBean();
		IDataCenter idc = BeanUtils.toDataCenter(param);
		Map<String, AppResultBean> resultMap = new HashMap<String, AppResultBean>();
		int errorCount = 0;
		try {

			List<AssetInfoVO> assetinfoList = (List<AssetInfoVO>) BeanUtils.jsonToBeans(idc, "assetinfos",
					AssetInfoVO.class);
			for (int i = 0; i < assetinfoList.size(); i++) {

				AssetInfoVO assetInfoVo = assetinfoList.get(i);
				AssetVO assetVo = changeAssetInfoVOtoAssetVo(assetInfoVo);
				assetVo.setAssetAllowedNum(LicInfoUtil.queryAssetAllowedNum(request));
				AssetAppendVO assetAppendVo = changeAssetInfoVOtoAssetAppendVo(assetInfoVo);

				SnmpVO assetSnmpVo = new SnmpVO();
				List<CustomPropertyVO> list = new ArrayList<CustomPropertyVO>();
				BorrowVO borrowVo = new BorrowVO();

				AssetRemoteConfigVO telnetVo = new AssetRemoteConfigVO();
				AssetRemoteConfigVO sshVo = new AssetRemoteConfigVO();
				AssetRemoteConfigVO wmiVo = new AssetRemoteConfigVO();
				AssetRemoteConfigVO trayVo = new AssetRemoteConfigVO();

				// telnet 0 SSH 1 wmi 2 tray 3
				if (telnetVo != null)
					telnetVo.setConnectType("0");
				if (sshVo != null)
					sshVo.setConnectType("1");
				if (wmiVo != null)
					wmiVo.setConnectType("2");
				if (trayVo != null)
					trayVo.setConnectType("3");
				assetVo.setOperator(getUserId(session));
				assetVo.setUserId(getUserId(session));

				// assetVo.setAssetAllowedNum(LicInfoUtil.queryAssetAllowedNum(request));

				String monitorIds = idc.getParameter("monitorId");
				String buttonType = (String) idc.getParameter("buttonType");
				if (StringUtils.isNotEmpty(monitorIds)) {
					// 停用监控器
					MonitorVO vo = new MonitorVO();
					vo.setPageSize(100000);
					vo.setCurrentPageNum(1);
					assetservice.updMonitorStatus(assetVo.getEdId(), vo);
				}
				assetservice.setBatch(false);
				AssetReturnVO errorInfo = assetservice.updAsset(assetVo, assetAppendVo, assetSnmpVo, list, borrowVo,
						telnetVo, sshVo, wmiVo, trayVo);

				// assetName = assetVo.getAssetName();
				if (errorInfo.getConflict() == 0) {
					// bean.ok("同步成功。");
					AppResultBean resultBean = new AppResultBean();
					resultBean.ok("同步修改成功。");
					resultMap.put(assetVo.getEdId(), resultBean);

					if ("next".equals(buttonType) && errorInfo.getConflict() == 0) {
						assetVo.setEdId(errorInfo.getEdId());
						AssetVO vo = assetservice.queryAssetDetailAdd(assetVo);
						vo.setIpList(null);
						vo.setAssetAppend(null);
						vo.setSnmp(null);
						vo.setCustomPropertyList(null);
						setStoreRowData(bean, "assetStore", vo);
					}
				} else if (errorInfo.getConflict() == 1) {
					String rtnMessage = "";
					for (AssetReturnVO error : errorInfo.getConfIPList()) {
						rtnMessage += "资产IP" + error.getIp() + "与域" + error.getDomainName() + "下的"
								+ error.getAssetName() + "的IP重复。";
					}
					AppResultBean resultBean = new AppResultBean();
					resultBean.fail(rtnMessage);
					resultMap.put(assetVo.getEdId(), resultBean);
					errorCount++;

				} else if (errorInfo.getConflict() == 2) {
					// errorReturnList.add("资产主IP与" + errorInfo.getDomainName()
					// + "下的网段" + errorInfo.getIpSection() + "有重复，请修改后再同步。");
					AppResultBean resultBean = new AppResultBean();
					resultBean.fail(
							"资产主IP与" + errorInfo.getDomainName() + "下的网段" + errorInfo.getIpSection() + "有重复，请修改后再同步。");
					resultMap.put(assetVo.getEdId(), resultBean);
					errorCount++;
				} else if (errorInfo.getConflict() == 3) {
					// errorReturnList.add("该资产正在被工单【" +
					// errorInfo.getProcInstName() + "】处理，不能修改资产状态。");
					AppResultBean resultBean = new AppResultBean();
					resultBean.fail("该资产正在被工单【" + errorInfo.getProcInstName() + "】处理，不能修改资产状态。");
					resultMap.put(assetVo.getEdId(), resultBean);
					errorCount++;
				} else if (errorInfo.getConflict() == 4) {
					// errorReturnList.add("资产所属的多个安全域必须隶属于不同的代理。<br>" +
					// errorInfo.getConflictMessage().toString());
					AppResultBean resultBean = new AppResultBean();
					resultBean.fail("资产所属的多个安全域必须隶属于不同的代理。" + errorInfo.getConflictMessage().toString());
					resultMap.put(assetVo.getEdId(), resultBean);
					errorCount++;
				} else if (errorInfo.getConflict() == 5) {
					AppResultBean resultBean = new AppResultBean();
					resultBean.fail("启用的资产数量已经达到License允许的最大数量，资产不能启用。");
					resultMap.put(assetVo.getEdId(), resultBean);
					errorCount++;
				} else if (errorInfo.getConflict() == 6) {
					AppResultBean resultBean = new AppResultBean();
					resultBean.fail("资产编号与资产名称为" + errorInfo.getAssetName() + "的资产编号重复，请修改后再同步。");
					resultMap.put(assetVo.getEdId(), resultBean);
					errorCount++;
				} else {
					AppResultBean resultBean = new AppResultBean();
					resultBean.fail("同步修改失败。");
					resultMap.put(assetVo.getEdId(), resultBean);
					errorCount++;
				}
			}
		} catch (Exception e) {
			bean.fail("同步修改失败。");
			logger.error(e.getMessage(), e);
		}
		bean.ok(resultMap);
		return bean;
	}

	/**
	 * 
	 * 删除某个资产
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("batchDelAsset")
	@ResponseBody
	public AppResultBean delAsset(@RequestParam("param") String param, HttpSession session) throws Exception {
		logger.info("param=[" + param + "]");
		AppResultBean bean = new AppResultBean();
		IDataCenter idc = BeanUtils.toDataCenter(param);
		List<AssetVO> assetList = new ArrayList<AssetVO>();
		Map<String, AppResultBean> resultMap = new HashMap<String, AppResultBean>();
		try {
			String edIds = idc.getParameter("deviceIds").toString();
			if (StringUtils.isEmpty(edIds)) {
				bean.fail("资产删除同步失败，参数错误" + edIds);
			}
			String assetIds[] = edIds.split(",");
			for (int i = 0; i < assetIds.length; i++) {
				List<AssetVO> resultList = assetservice.queryMonitorVsEd(assetIds[i]);
				if (resultList.size() > 0) {
					AppResultBean resultBean = new AppResultBean();
					resultBean.fail("资产已经配置监控器，无法删除");
					resultMap.put(assetIds[i], resultBean);
				} else {
					AssetVO vo = new AssetVO();
					vo.setEdId(assetIds[i]);
					vo.setOperator(getUserId(session));
					vo.setUserId(getUserId(session));
					assetList.add(vo);
				}
			}
			if (assetList.size() > 0) {
				assetservice.delAsset(assetList);
				for (int i = 0; i < assetList.size(); i++) {
					AppResultBean resultBean = new AppResultBean();
					resultBean.ok("资产删除同步成功");
					resultMap.put(assetList.get(i).getEdId(), resultBean);
				}
			}
			logger.info("batchDelAsset -> " + JsonUtil.write(resultMap));
			bean.ok(resultMap);
		} catch (AppException e) {
			bean.fail("资产同步删除失败。");
			logger.error(e.getMessage(), e);
		}
		return bean;
	}

	/**
	 * 
	 * @param assetVO
	 * @return
	 */
	private AssetVO changeAssetInfoVOtoAssetVo(AssetInfoVO assetInfoVO) {
		AssetVO assetVO = new AssetVO();
		assetVO.setEdId(assetInfoVO.getDeviceId());// 设备标识
		assetVO.setAssetName(assetInfoVO.getDeviceName());// 设备名称
		assetVO.setAssetTypeId(assetInfoVO.getType());// 设备类型
		assetVO.setOsType(assetInfoVO.getOs());// 操作系统
		assetVO.setSecurityDomainId(assetInfoVO.getSystemId());// 系统标识 对应安全域
		assetVO.setAssetDesc(assetInfoVO.getDescription());// 设备描述
		assetVO.setSupplierId(assetInfoVO.getManufactory());// 厂家
		assetVO.setAssetModel(assetInfoVO.getProductType());// 产品型号
		assetVO.setContractorsCode(assetInfoVO.getVendor());// 供应商
		assetVO.setMainIp(assetInfoVO.getIp());// IP
		assetVO.setMainMac(assetInfoVO.getMac());// MAC地址
		assetVO.setAssetValue(assetInfoVO.getDeviceValue());// 设备价值
		assetVO.setAssetStatus("0");// 资产状态 0位启用
		assetVO.setSnmpStatus("0");// snmp开通状态 默认0 未开通
		assetVO.setIsOperationAsset("1");
		assetVO.setIsComputeRisk("1");

		List<IpVO> list = new ArrayList<IpVO>();

		if (StringUtil.isNotEmpty(assetInfoVO.getIp())) {
			// 封装ipvo列表
			IpVO ipVo = new IpVO();
			ipVo.setIpType("4");
			ipVo.setIpV4(assetInfoVO.getIp());
			ipVo.setKeyIp("1");// 设置为主IP
			ipVo.setMac(assetInfoVO.getMac());
			list.add(ipVo);
		}
		assetVO.setIpList(list);
		return assetVO;
	}

	/**
	 * @param assetVO
	 * @return
	 */
	private AssetAppendVO changeAssetInfoVOtoAssetAppendVo(AssetInfoVO assetInfoVO) {
		AssetAppendVO assetAppendVO = new AssetAppendVO();
		assetAppendVO.setEdId(assetInfoVO.getDeviceId());// 资产编号
		assetAppendVO.setBuyDate(assetInfoVO.getBuyTime());// 购买日期
		assetAppendVO.setHardwareVersion(assetInfoVO.getHardwareVersion());// 硬件版本
		assetAppendVO.setFirmwareVersion(assetInfoVO.getFirmwareVersion());// 固件版本
		return assetAppendVO;
	}

}
